package yxy.cherry.paycenter.servlet.channel.xiaomi_quick;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jodd.util.StringUtil;
import yxy.apple.logger.Logger;
import yxy.apple.util.HmacSHA1Encryption;
import yxy.apple.util.MD5Utility;
import yxy.apple.util.SdkUtil;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.charge;
import yxy.cherry.paycenter.channelmodule.ActType;
import yxy.cherry.paycenter.channelmodule.sdk_vivo_quick.PayMoudle_vivo_quick;
import yxy.cherry.paycenter.database.dao.orderinfoDao;
import yxy.cherry.paycenter.database.dao.ordersDao;
import yxy.cherry.paycenter.database.db.orderinfo;
import yxy.cherry.paycenter.database.db.orders;
import yxy.cherry.paycenter.servlet.channel.Servlet;
import yxy.cherry.paycenter.util.HttpUtil;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.channel.SdkChannel;
import yxy.game.pm2.bean.db.sdk.SDK_UnionChannel;
import yxy.game.pm2.bean.db.sdk.SDK_UnionChannelDAO;
import yxy.game.pm2.bean.module.OrderInfoModule;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

//xiaomi快游戏，支付结果通知
public class Servlet_xiaomi_quick extends Servlet{
	private static final Logger logger = Logger.create(Servlet_xiaomi_quick.class);
	@Override
	public String getChannel() {
		return SdkChannel.sdk_xiaomi_quick;
	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doGet(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		JSONObject rjson = new JSONObject();
		rjson.put("errcode", 200);
		rjson.put("errMsg", "success");
		try {
			JSONObject json = HttpUtil.getParseJSON(req);
			logger.info(SdkChannel.sdk_vivo_quick + ":notify:" + json.toJSONString());

			String appId = json.getString("appId");
			String cpOrderId = json.getString("cpOrderId"); //我方订单号
			String cpUserInfo = json.getString("cpUserInfo"); //开发商透传信息
			String uid = json.getString("uid"); //渠道方uid
			String orderId = json.getString("orderId"); //渠道方订单号
			String orderStatus = json.getString("orderStatus"); //订单状态，TRADE_SUCCESS 代表成功
			String payFee = json.getString("payFee"); //分
			String productCode = json.getString("productCode");
			String productName = json.getString("productName");
			String productCount = json.getString("productCount");
			String payTime = json.getString("payTime");
			String partnerGiftConsume = json.getString("partnerGiftConsume");
			String signature = json.getString("signature");

			if (!orderStatus.equals("TRADE_SUCCESS")) throw new Exception("订单状态错误：" + orderStatus);
			//基础参数校验
			if (StringUtil.isAllEmpty(appId, cpOrderId, orderId, payFee))
				throw new Exception("参数异常");
			//myorderid 为空
			if(!StringUtil.isEmpty(cpOrderId)) {
				orderinfo oinfo = new orderinfo();
				oinfo.setMyorderid(cpOrderId);
				oinfo.setOtherinfo(json.toString());
				orderinfoDao.add(oinfo);
			}
			//渠道参数核对
			SDK_UnionChannel unionChannel = SDK_UnionChannelDAO.getByAppId(SdkChannel.sdk_xiaomi_quick, appId);
			if (unionChannel == null) throw new Exception("渠道异常");
			//订单核对，是否存在
			orders o = ordersDao.getOrderByMyorderid(cpOrderId);
			if (o == null) throw new Exception("订单不存在");
			//已经是成功的订单，不用重复处理
			if (o.getOrderstate() == 1) {
				returnInfo(rjson, resp);
				return;
			}
			//金额核对
			int fee = Integer.parseInt(payFee);
			if (fee != o.getGoodsprice()) throw new Exception("amount error");

			//sign校验
			Map<String, String> params = json.toJavaObject(Map.class);
			params.remove("signature");
			String signContent = SdkUtil.mapToContent(params, false);
			String makeSign = HmacSHA1Encryption.HmacSHA1Encrypt(signContent, unionChannel.getAppSecret());
			logger.info(SdkChannel.sdk_vivo_quick + ":sign:%s,%s,%s,%s", JSON.toJSON(params), signContent, makeSign);
			if (!makeSign.equals(signature)) throw new Exception("sign error");

			o.setPlatorderid(orderId);
			o.setUpdatetime(new Date());
			o.setPayamount(fee);
			o.setOrderstate(OrderInfoModule.orderinfofinish);
			ordersDao.update(o);

			ActType at = ActType.getat(o.getActtype());
//		PayType pt = PayType.getpt(at.getPaytype());
			PayMoudle_vivo_quick am = new PayMoudle_vivo_quick();
			ArrayList<Currency> curs = am.getRewardInfoByType(o.getPlayercode(), at, o.getGoodsid());

			charge charge = DataCenter.getData(o.getGoodsid(), charge.class);
			am.createOrderInfoModule(o, curs, charge.getVipexp(), o.getGoodsprice());

			returnInfo(rjson, resp);
		} catch (Exception e) {
			logger.error(SdkChannel.sdk_vivo_quick + ":sign error:%s", e);
			e.printStackTrace();

			rjson.put("errcode", 500);
			rjson.put("errMsg", e.getMessage());
			returnInfo(rjson, resp);
		}
	}
}
